/**
 * 141. 环形链表
 * https://leetcode-cn.com/problems/linked-list-cycle/
 */
public class Solutions_141 {
    public static void main(String[] args) {
//        int[] arr = {3, 2, 0, -4};
//        int pos = 1;  // output: true

//        int[] arr = {1, 2};
//        int pos = 0;  // output: true

        int[] arr = {1};
        int pos = -1;  // output: false

        ListNode head = MyLinkedListUtils.ArrayToListNode(arr, pos);
        boolean result = hasCycle(head);
        System.out.println(result);
    }

    public static boolean hasCycle(ListNode head) {
        // 定义快慢指针
        ListNode slow = head, fast = head;
        // 若快慢指针能够相遇，那么 head 存在环
        while (fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
            if (fast == slow) {
                return true;
            }
        }
        // 否则不存在
        return false;
    }
}
